package com.slife.snap.service;

import com.fazecast.jSerialComm.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class SerialCmdLineRunner implements CommandLineRunner {

    @Autowired
    private SerialListenerService listenerService;

    private      String portName = "ttyUSB0";


    private final ConcurrentHashMap<String, SerialPort> serialPortMap = new ConcurrentHashMap<>();

    @Override
    public void run(String... args) throws Exception {

        List<String> portNames = listenerService.getPortNames();

        System.out.println("SerialService ------------  get ports ");
        for (String key: portNames) {

            System.out.println(key);
        }
        SerialPort currentPort = listenerService.openDevice(portName);
        if (null == currentPort){
            System.out.println("打开设备失败，请检查设备后重试！");
        }
        System.out.println("当前串口："+currentPort);
        serialPortMap.put(portName, currentPort);
    }

    @PreDestroy
    public void destory() {
        serialPortMap.get(portName).closePort();
    }

}
